using FytSoa.Application.Erp.Param;
using FytSoa.Common.Enum;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-采购退货服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpPurchaseReturnService : IApplicationService 
{
    private readonly SugarRepository<ErpPurchaseReturn> _thisRepository;
    private readonly ErpOperateLogService _operateLogService;
    private readonly ErpFlowUseService _flowUseService;
    public ErpPurchaseReturnService(SugarRepository<ErpPurchaseReturn> thisRepository
        ,ErpOperateLogService operateLogService
        ,ErpFlowUseService flowUseService)
    {
        _thisRepository = thisRepository;
        _operateLogService = operateLogService;
        _flowUseService = flowUseService;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpPurchaseReturnDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id!=0,m=>m.SupplierId==param.Id)
            .WhereIF(!string.IsNullOrEmpty(param.Status),m=>m.Status==(ErpAuditEnum)int.Parse(param.Status))
            .Includes(m=>m.Supplier)
            .Includes(m=>m.Order)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ErpPurchaseReturnDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpPurchaseReturnDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.Supplier)
            .Includes(m=>m.Order)
            .FirstAsync(m=>m.Id==id);
        var result=model.Adapt<ErpPurchaseReturnDto>();
        result.Flow = await _flowUseService.GetFlowAsync(model.Id);
        return result;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(ErpPurchaseReturnDto model)
    {
        var toDay = await _thisRepository.CountAsync(m=>SqlFunc.DateIsSame(m.CreateTime,DateTime.Now));
        model.Number = "CR".ResNumber(toDay);
        var addId=await _thisRepository.InsertReturnSnowflakeIdAsync(model.Adapt<ErpPurchaseReturn>());
        
        await _operateLogService.AddAsync(new ErpOperateLogDto()
        {
            OperateId = addId,
            Type = (int)ErpOperateEnum.PurchaseOrder,
            Remark = "创建了采购退货信息【"+model.Number+"】"
        });
        
        if (model.FlowId!=0)
        {
            await _flowUseService.AddAsync(new ErpFlowUseDto()
            {
                FlowId=model.FlowId,
                UseId=addId,
                Type = FlowTypeEnum.PurchaseReturn,
            });
        }
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyAsync(ErpPurchaseReturnDto model)
    {
        await _thisRepository.UpdateAsync(model.Adapt<ErpPurchaseReturn>());
        if (model.Status == ErpAuditEnum.NotReviewed)
        {
            await _flowUseService.ModifyAsync(new ErpFlowUseDto()
            {
                FlowId = model.FlowId,
                UseId = model.Id,
                Type = FlowTypeEnum.PurchaseReturn,
            });
        }
    }

    /// <summary>
    /// 修改状态
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyStatusAsync(ErpStatusParam param)
    {
        await _thisRepository.UpdateAsync(m=>new ErpPurchaseReturn()
        {
            Status = param.Status
        },m=>param.Ids.Contains(m.Id));
        #region 处理库存减少
        /*var productStockRepository = _thisRepository.ChangeRepository<SugarRepository<ErpProductStock>>();
        var returnInfoRepository = _thisRepository.ChangeRepository<SugarRepository<ErpPurchaseReturnInfo>>();
        var returnList = await returnInfoRepository.GetListAsync(m => m.ReturnId == id);
        var productIds = returnList.Select(m => m.ProductId);
        //查询真正库存信息
        var productList = await productStockRepository.GetListAsync(m => productIds.Contains(m.ProductId));
        foreach (var item in productList)
        {
            var returnModel = returnList.FirstOrDefault(m => m.ProductId == item.ProductId);
            item.Count -= returnModel.Count;
        }

        await productStockRepository.UpdateRangeAsync(productList);*/
        #endregion
        await _operateLogService.AddAsync(new ErpOperateLogDto()
        {
            OperateIds = param.Ids,
            Type = (int)ErpOperateEnum.PurchaseReturn,
            Remark = "对采购退货做了审核通过操作"
        });
        
        if (param.Status==ErpAuditEnum.InReview)
        {
            foreach (var item in param.Ids)
            {
                await _flowUseService.StartAuditAsync(item, FlowTypeEnum.PurchaseReturn);
            }
        }
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete,UnitOfWork]
    public async Task DeleteAsync([FromBody] List<long> ids)
    {
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
        var returnInfoRepository = _thisRepository.ChangeRepository<SugarRepository<ErpPurchaseReturnInfo>>();
        await returnInfoRepository.DeleteAsync(m => ids.Contains(m.ReturnId));
        await _flowUseService.DeleteAsync(ids);
    }
}
